﻿using MetroDataApi.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace MetroDataApi.Controllers.Management
{
    public class AddProjectController : ApiController
    {


        private string GetOwnerCorp(string location, string prjType)
        {
            var dict = new Dictionary<string, string>();
            dict.Add("上海", "上海地铁");
            dict.Add("南京", "南京地铁");
            dict.Add("RoadTunnelMonitor", "路政局");
            dict.Add("Volkswagen", "大众");
            if (dict.ContainsKey(prjType))
            {
                return dict[prjType];
            }
            else
            {
                return dict[location];
            }

        }

        public string Delete(int prjId)
        {
            ProjectsHelper.DeleteProjectById(prjId);
            return "";
        }


        public string Post([FromBody] string value)
        {
            JObject jsonData = JObject.Parse(value);
            var prjName = jsonData["prjName"].ToString();
            var lineName = jsonData["lineName"].ToString();
            var cityName = jsonData["cityName"].ToString();
            var projectType = jsonData["projectType"].ToString();

            var corporation = jsonData["corporation"].ToString();
            var department = jsonData["department"].ToString();




            using (var db = new MetroDataDataContext())
            {
                var prr = new Projects()
                {
                    LineId = db.Lines.Single(a => a.Locate == cityName && a.Name == lineName).Id,
                    Location = cityName,
                    Name = prjName,
                    PrjId = db.Projects.Max(p => p.PrjId) + 1,
                    Status = 1,
                    ProjectType = projectType
                };
                db.Projects.InsertOnSubmit(prr);
                var extraInfo = new MonitorProjectExtraInfo()
                {
                    PrjId = prr.PrjId,
                    PrjLevel = "一级",
                    PrjState = "新增",
                    PrjSummary = "暂未上传",
                    TunnelType = "单圆隧道",
                    ConstructionCorp = corporation,
                    Department = department,
                    OwnerCorp = GetOwnerCorp(prr.Location, prr.ProjectType)
                };
                db.MonitorProjectExtraInfo.InsertOnSubmit(extraInfo);
                db.SubmitChanges();
                MetroDataQuery.Utility.MetroDataBaseUtility.AddMonitorPointsTables(prr.PrjId);
                return JsonConvert.SerializeObject(prr, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
            }
        }
    }
}
